#include "UdpSocket.hpp"
// C 式写法
typedef void (*Handler)(const std::string& req, std::string* resp);
// C++ 11 式写法, 能够兼容函数指针, 仿函数, 和 lamda
//#include <functional>
//typedef std::function<void(const std::string &, std::string *resp)> Handler;
class UdpServer
{
public:
    UdpServer(const std::string &ip, const uint16_t port,const Handler handler)
    :sock_(ip,port), handler_(handler)
    {
        
    }
    ~UdpServer()
    {

    }
    bool Start()
    {
        while(true)
        {
            // 尝试读取请求
            std::string req;
            std::string remote_ip;
            uint16_t remote_port = 0;
            bool ret = sock_.RecvFrom(&req, &remote_ip, &remote_port);//监听客户端
            if (!ret)
            {
                continue;
            }
            // 根据请求计算响应
            std::string resp;
            handler_(req, &resp);
            sock_.SendTo(resp, remote_ip, remote_port);// 返回响应给客户端
            printf("[%s:%d] req: %s, resp: %s\n", remote_ip.c_str(), remote_port,
                   req.c_str(), resp.c_str());
        }
        return true;
    }

private:
    UdpSocket sock_;
    Handler handler_;
};